package com.yy.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

/**
 * @Description:
 * @ClassName: CronUtil
 * @author: 姚欣宏
 * @date: 2023.07.11
 */
public class CronUtil {
    public static void main(String[] args) {
        System.out.println(generateCronExpressionForOnce("2023-07-11 08:01:01"));
        System.out.println(backTime("2023-07-11 08:01:01",300));
    }
    public static String generateCronExpressionForOnce(String dateString) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf.parse(dateString);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            int minute = calendar.get(Calendar.MINUTE);
            int second = calendar.get(Calendar.SECOND);
            return String.format("%d %d %d %d %d ? %d", second, minute, hour, day,month, year);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }
    public static String backTime(String dateTimeString,Integer back){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);

        LocalDateTime twoMinutesAgo = dateTime.minusSeconds(back);

        String formattedDateTime = twoMinutesAgo.format(formatter);
        return formattedDateTime;
    }
}
